-
-
Notifications
You must be signed in to change notification settings - Fork 850
Chapter 1 #520
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Chapter 1 #520
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great work! Thanks for taking your time to finish the Chapter 😊
@@ -490,7 +490,8 @@ Implement a function that returns the last digit of a given number. | |||
whether it works for you! | |||
-} | |||
-- DON'T FORGET TO SPECIFY THE TYPE IN HERE | |||
lastDigit n = error "lastDigit: Not implemented!" | |||
lastDigit :: Int -> Int | |||
lastDigit x = mod x 10 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Your implementation is almost correct 🆗
Unfortunately, it returns negative numbers on negative inputs because of how mod
works. Sometimes corner cases can be tricky to spot and fix...
sumLast2 n = let last = mod n 10 | ||
seclast = mod (div n 10) 10 -- div n 10 gives the digit stripped off last digit. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That is a wonderful solution! 👏🏼 You correctly noticed that it is the div
and mod
, cool 😎
One hint to make your solution even shorter: you can see that you use both:
mod m 10
div m 10
The standard library has the divMod
function, that actually combines inside both div
and mod
. And this is exactly what you use!.
So you could write it this way:
(x, y) = divMod m 10
You can see how we could pattern match on the pair 🙂
firstDigit n = error "firstDigit: Not implemented!" | ||
|
||
firstDigit :: Int -> Int | ||
firstDigit n = if n < 10 then n else firstDigit (div n 10) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see, that for a negative number like -19, this implementation will return the negative number itself instead of the last digit because the first check n < 10 will always succeed for negative numbers.
Solutions for Chapter 1
cc @vrom911 @chshersh